﻿namespace CSharpTest
{
    class BlockingDequeue
    {
        static string redisHost = "192.168.0.61";
        static int id = 1;
        static int db = 2;
        static string listId = "test_list2";
        /// <summary>
        /// 主函数
        /// </summary>
        /// <param name="args"></param>
        static void Main1(string[] args)
        {
            Console.WriteLine("输入（【0】显示Redis队列数据，【1】追加Redis队列）：");
            var keyInfo = Console.ReadKey(true);
            if (keyInfo.KeyChar == '0')
            {
                Console.WriteLine("显示Redis队列数据：");
                foreach (var item in GetRedisData())
                {
                    Console.WriteLine($"取出数据【{item}】！");
                }
                Console.WriteLine("按任意键退出！");
                Console.ReadKey();
                return;
            }
            if (keyInfo.KeyChar == '1')
            {
                Console.WriteLine("追加Redis队列：");
                foreach (var item in PushRedisData(() => Console.ReadLine()))
                {
                    Console.WriteLine($"数据【{item}】已存入Redis!");
                }
                return;
            }
            Console.WriteLine("不能识别的操作！");
        }

        static IEnumerable<Message> PushRedisData(Func<string> strCreator)
        {
            using (RedisClient client = new RedisClient(redisHost))
            {
                client.ChangeDb(db);
                var carClient = client.As<Message>();
                var redisList = carClient.Lists[listId];
                string msg = null;
                while (msg != "exit")
                {
                    msg = strCreator();
                    var message = new Message { Id = id++, Cmd = msg };
                    carClient.EnqueueItemOnList(redisList, message);
                    yield return message;
                }
            }
        }
        static IEnumerable<Message> GetRedisData()
        {
            using (RedisClient client = new RedisClient(redisHost))
            {
                client.ChangeDb(db);
                var carClient = client.As<Message>();
                var redisList = carClient.Lists[listId];
                string msg = null;
                while (msg != "exit")
                {
                    var car = carClient.BlockingDequeueItemFromList(redisList, null);
                    msg = car.Cmd;
                    yield return car;
                }
            }
        }

    }
    class Message
    {
        // test_list列表  {"Id":1,"Cmd":"EEE"}
        public int Id { get; set; }
        public string Cmd { get; set; }
        public override string ToString()
        {
            return $"Id:{Id} Cmd:{Cmd}";
        }
    }
}
